package com.it.xyx.demo.service.impl;

import com.it.xyx.demo.api.AccountFeignApi;
import com.it.xyx.demo.entity.Order;
import com.it.xyx.demo.mapper.OrderMapper;
import com.it.xyx.demo.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xyx
 * @since 2024-08-22
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Resource
    private OrderMapper orderMapper;
    @Resource//订单微服务通过OpenFeign去调用支付微服务
    private AccountFeignApi accountFeignApi;

    @Override
    @GlobalTransactional(name = "zzyy-create-order", rollbackFor = Exception.class) //AT
    public void create(Order order) {
        //xid检查
        String xid = RootContext.getXID();
        System.out.println("==================>开始新建订单" + "\t" + "xid_order:" + xid);
        //订单状态status：0：创建中；1：已完结
        order.setStatus(0);
        int result = orderMapper.insert(order);
        //插入订单成功后获得插入mysql的实体对象
        Order orderFromDB = null;
        if (result > 0) {
            orderFromDB = orderMapper.selectById(order.getId());
            System.out.println("-------> 新建订单成功，orderFromDB info: " + orderFromDB);
            long num = 100;
            accountFeignApi.decrease(orderFromDB.getUserId(), num);
            System.out.println("-------> 订单微服务结束调用Account账号，做扣减完成");
        }
    }
}
